package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author ChuMingYu
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 添加菜品
     *
     * @param
     * @return
     */
    @PostMapping
    public R saveDish(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        //清理某个分类下的菜品缓存
        String key = "dish"+dishDto.getCategoryId()+"1";
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    /**
     * 分页查询菜品
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R selectDishByPage(Integer page, Integer pageSize, String name) {
        //创建分页构造器
        IPage<Dish> dishPage = new Page<>(page, pageSize);

        //创建条件构造器
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();

        //添加分页查询条件
        qw.like(name != null, Dish::getName, name);
        qw.orderByDesc(Dish::getUpdateTime);

        //查询
        dishService.page(dishPage, qw);
        long total = dishPage.getTotal();
        List<Dish> records = dishPage.getRecords();
        Map map = new HashMap();
        map.put("total", total);
        //map.put("records",records);
        List<DishDto> dishDtos = new ArrayList<>();
        for (Dish dish : records) {
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            DishDto dishDto = new DishDto();
            dishDto.setCategoryName(categoryName);
            BeanUtils.copyProperties(dish, dishDto);
            dishDtos.add(dishDto);
        }
        map.put("records", dishDtos);
        log.info(map.toString());
        return R.success(map);
    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R selectDishById(@PathVariable Long id) {
        //1、查询菜品数据 select * from dish where id = ?
        LambdaQueryWrapper<Dish> dishQW = new LambdaQueryWrapper<>();
        dishQW.eq(Dish::getId,id);
        Dish dish = dishService.getOne(dishQW);

        //2、查询菜品对应的口味数据 select * from dish_flavor where dish_id = ?
        LambdaQueryWrapper<DishFlavor> dishFlavorQW= new LambdaQueryWrapper<>();
        dishFlavorQW.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> list = dishFlavorService.list(dishFlavorQW);

        //返回DishDto对象，先new出该对象 DishDto dishDto = new DishDto();
        DishDto dishDto = new DishDto();

        // 把dish菜品数据 赋值/拷贝 给 dishDto对象 BeanUtils.copyProperties
        BeanUtils.copyProperties(dish,dishDto);

        // 设置dishDto的口味数据 dishDto.setFlavors(xxx)
        dishDto.setFlavors(list);

        // 返回数据 ;
        return R.success(dishDto);

    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R updateDish(@RequestBody DishDto dishDto){
        // 1、修改菜品dish表的数据
        Long dishDtoId = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
        dishService.updateById(dishDto);

        //取出菜品id Long dishId = dishDto.getId();
        // 2、修改菜品的口味数据 如何完成？？
        // 2.1 先删除原有的口味数据: delete from dish_flavor where dish_id = ?
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishDtoId);
        dishFlavorService.remove(dishFlavorLambdaQueryWrapper);

        // 2.2 添加菜品口味数据 List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item)->{
            item.setDishId(dishDtoId);
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
        //清理所有菜品的缓存数据
        //获取所有以dish_xxx开头的key
        Set keys = redisTemplate.keys("dish_*");
        //删除这些key
        redisTemplate.delete(keys);

        return  R.success("修改菜品成功");
    }

    /**
     * 删除菜品/批量删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R delectDishByIds(@RequestParam List<Long> ids){
        log.info(ids.toString());
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.in(Dish::getId,ids);
        dishService.remove(dishLambdaQueryWrapper);
        return R.success("删除成功");
    }

    /**
     * 起售/停售 批量起售/批量停售
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R updateDishStatus(@PathVariable Integer status,@RequestParam List<Long> ids){
        // update dish set status = ? where id in (1,2,3)
        LambdaUpdateWrapper<Dish> dishLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        dishLambdaUpdateWrapper.set(Dish::getStatus,status);
        dishLambdaUpdateWrapper.in(Dish::getId,ids);
        dishService.update(dishLambdaUpdateWrapper);
        return R.success("操作成功");
    }

    /**
     * 根据分类id查询该分类下的所有菜品集合
     * @param
     * @return
     */
    @GetMapping("/list")
    public R selectDishInCategory(Dish dish){
        //先从redis中查询,如果有数据直接返回
        List<DishDto> dishDtoList = null;
        String key = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(dishDtoList != null){
            //如果存在，直接返回，无需查询数据库
            return R.success(dishDtoList);
        }

        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        dishLambdaQueryWrapper.eq(Dish::getStatus,1);
        dishLambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(dishLambdaQueryWrapper);
        log.info(list.toString());

        dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());
        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到Redis
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }
}
